package com.yt.system.controller;

import com.yt.system.domain.Account;
import com.yt.system.domain.History;
import com.yt.system.domain.Week;
import com.yt.system.domain.WeekScore;
import com.yt.system.service.AccountService;
import com.yt.system.service.HistoryService;
import com.yt.system.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ShiYuNan
 */
@Api(tags = "个人加减分记录管理")
@RestController
public class HistoryController {
    @Autowired
    HistoryService historyService;
    @Autowired
    AccountService accountService;

    /**
     * 根据用户ID查询历史积分记录
     * @param aid
     * @return
     */
    @ApiOperation(value = "根据用户ID查询历史积分记录")
    @GetMapping("/history/{aid}")
    public List<History> getHistoryByAid(@PathVariable("aid") Integer aid){
        return historyService.selectByAid(aid);
    }

    /**
     * 查询所有积分记录
     * @return
     */
    @ApiOperation(value = "查询所有积分记录")
    @GetMapping("/histories")
    public List<History> getAllHistory(){
        return historyService.selectAllHistory();
    }

    /**
     * 插入积分记录
     * @param record
     * @return
     */
    @ApiOperation(value = "插入积分记录")
    @PostMapping("/insertHistory")
    public String insertHistory(History record) {
        try {
            //获取用户当前的积分
            Double score = historyService.selectScoreByAid(record.getAid());
            Double operateScore = record.getOperatesorce();
            score+=operateScore;
            record.setTotalchange(score);
            historyService.insert(record);
            Account account = new Account();
            account.setAid(record.getAid());
            account.setAintegral(score);
            historyService.updateByPrimaryKeySelective(account);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     *根据时间查询所有人本周的积分并排序----本周积分排行
     * @param
     * @return
     */
    @ApiOperation(value = "根据时间查询所有人本周的积分并排序----本周积分排行榜")
    @GetMapping("/selectByTime")
    public List<WeekScore> selectByTime(){
        //获取当前日期和本周一的日期
        TimeUtil timeUtil = new TimeUtil();
        Map<String, Date> map = timeUtil.getMondayAndCurday();
        //根据周一和当前日查询出所有加减分记录
        List<History> list = historyService.selectByTime(map);
        //初始化一个列表来暂存用户ID
        List<Integer> ids = new ArrayList();
        //初始化一个列表来存用户的WeekScore对象
        List<WeekScore> list1 = new ArrayList<>();
        //遍历所有用户的加减分记录
        for(History history:list){
            //将每一条记录的ID存到暂存列表中
            ids.add(history.getAid());
        }
        //去重
        List<Integer> list2 = ids.stream().distinct().collect(Collectors.toList());
        //去重后遍历
        for(Integer abc:list2){
            //查询每个用户的ID和统计后的总分
            WeekScore weekScore = selectByTime(abc);
            //加进列表中

            list1.add(weekScore);
        }
        //把记录按照积分从大到排列
        Collections.sort(list1, new Comparator<WeekScore>() {
            private WeekScore w1;
            private WeekScore w2;

            @Override
            public int compare(WeekScore w1, WeekScore w2) {
                this.w1 = w1;
                this.w2 = w2;
                //降序
                return w2.getAintegral().compareTo(w1.getAintegral());
            }
        });
        int i=1;
        for(WeekScore weekScore:list1){
            weekScore.setNumber(i);
            i++;
        }
        //返回
        return list1;
    }
    /**
     *根据时间查询个人的历史积分记录----个人本周积分
     * @param aid
     * @return
     */
    @ApiOperation(value = "根据时间查询个人的历史积分记录----个人本周积分（有排名）")
    @GetMapping("/selectRankAndScore/{aid}")
    public WeekScore selectRankAndScore(@PathVariable("aid") Integer aid){
        List<WeekScore> lw = selectByTime();
        WeekScore weekScore = new WeekScore();
        for(WeekScore w:lw){
            if(w.getAid().equals(aid)){
                weekScore = w;
            }
        }
        return weekScore;
    }

    /**
     * 根据ID获取个人本周积分，无排名
     * @param aid
     * @return
     */
    public WeekScore selectByTime(Integer aid){
        //获取当前日期和本周一的日期
        TimeUtil timeUtil = new TimeUtil();
        Map<String, Date> map = timeUtil.getMondayAndCurday();
        //根据周一和当前日查询出所有加减分记录
        List<History> list = historyService.selectByTime(map);
        //初始化一个列表，用来装特定用户在本时间段的数据
        List<History> histories = new ArrayList<>();
        //初始化一个总积分
        Double total = 0.0;
        //遍历所有用户的加减分记录
        for(History history:list){
            //根据传入的ID将该用户在本时间段的数据存入一个列表
            if(history.getAid().equals(aid)){
                histories.add(history);
            }
        }
        //遍历传入ID的用户的加减分记录
        for(History history:histories){
            //统计加减分
            Double operatescore = history.getOperatesorce();
            total+=operatescore;
        }
        //封装一个对象，存排名、ID、名字和积分（ps:因为后期才想到，数据库没有表）
        WeekScore weekScore = new WeekScore();
        //设定ID为传过来的ID
        weekScore.setAid(aid);
        //传入名字
        weekScore.setAacount(accountService.selectByPrimaryKey(aid).getAacount());
        //将统计后的总分设进去
        weekScore.setAintegral(total);
        return weekScore;
    }

    /**
     * 按日期显示个人加分记录
     * @param aid
     * @return
     */
    @ApiOperation(value = "按日期显示个人加分记录")
    @GetMapping("/selectHistoryByDay/{aid}")
    public Map<String,List<History>> selectHistoryByDay(@PathVariable("aid") Integer aid){
        //初始化一个Map
        Map<String,List<History>> map = new TreeMap<>();
        //根据传入的ID查询出该用户的加减分记录并存入列表
        List<History> list = historyService.selectByAid(aid);
        //初始化一个列表暂存日期
        List<String> dates = new ArrayList<>();
        //设置时间格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        //遍历该用户的加减分记录
        for(History history:list){
            //转格式并加到日期暂存列表中
            dates.add(sdf.format(history.getOperatetime()));
        }
        //列表中的日期去重
        List<String> dates1 = dates.stream().distinct().collect(Collectors.toList());
        //遍历已经去重的日期列表
        for(String str:dates1){
            //初始一个列表用来存一个日期的数据
            List<History> list1 = new ArrayList<>();
            //遍历该用户的加减分记录
            for(History history1:list){
                //获取日期转格式后进行比较
                if(sdf.format(history1.getOperatetime()).equals(str)){
                    list1.add(history1);
                }
            }
            //map的key就是某年某月某日
            //存入map中
            map.put(str,list1);
        }
        //返回
        return map;
    }

    /**
     * 查询个人本周一到周日的加减分情况
     * @param aid
     * @return
     */
    @ApiOperation(value = "查询个人本周一到周日的加减分情况")
    @GetMapping("/getPerDateScoreByAid/{aid}")
    public Week getPerDateScoreByAid(@PathVariable("aid") Integer aid){
        //获取当前日期和本周一的日期
        TimeUtil timeUtil = new TimeUtil();
        Map<String, Date> map = timeUtil.getMondayAndCurday();
        List<History> list = historyService.selectByAid(aid);
        //设置时间格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String monday = sdf.format(map.get("monday"));
        String tuesday = sdf.format(map.get("tuesday"));
        String wensday = sdf.format(map.get("wensday"));
        String thursday = sdf.format(map.get("thursday"));
        String friday = sdf.format(map.get("friday"));
        String saturday = sdf.format(map.get("saturday"));
        String sunday = sdf.format(map.get("sunday"));
        Week week = new Week(0.0,0.0,0.0,0.0,0.0,0.0,0.0);
        for (History history1:list){
            Double fs = history1.getOperatesorce();
            if(sdf.format(history1.getOperatetime()).equals(monday)){
                week.setMonday(week.getMonday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(tuesday)){
                week.setTuesday(week.getTuesday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(wensday)){
                week.setWensday(week.getWensday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(thursday)){
                week.setThursday(week.getThursday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(friday)){
                week.setFriday(week.getFriday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(saturday)){
                week.setSaturday(week.getSaturday()+fs);
            }else if(sdf.format(history1.getOperatetime()).equals(sunday)){
                week.setSunday(week.getSunday()+fs);
            }
        }
        return week;
    }


}
